package my.iterator.composite;

import java.util.Iterator;
import java.util.Stack;
/**
 * 组合遍历（树节点） 需要递归
 */
public class CompositeIterator implements Iterator {
    //利用栈实现递归
    private Stack<Iterator> stack = new Stack<>();
    public CompositeIterator(Iterator iterator){
        stack.push(iterator);
    }
    @Override
    public boolean hasNext() {
        if(stack.isEmpty()){
            return false;
        }
        //从栈中获取一个不删除
        Iterator iterator = stack.peek();
        if(!iterator.hasNext()){
            //出栈删除
            stack.pop();
            return hasNext();
        }
        return true;
    }
    @Override
    public Object next() {
        if(hasNext()){
            Iterator iterator = stack.peek();
            MenuComponent menuComponent = (MenuComponent)iterator.next();
            if(menuComponent instanceof Menu){
                stack.push(menuComponent.createIterator());
            }
            return menuComponent;
        }
        return null;
    }
}
